package com.d16_Socket_Homework.homework5;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class ThreadSocket implements Runnable{
    private Socket socket;
    public ThreadSocket(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        try {
            //通过Socket获取输入流，读取网络中的数据
            BufferedInputStream bis = new BufferedInputStream(
                    socket.getInputStream());
            //开流指向本地文件--写到文件中
            bos = new BufferedOutputStream(
                    new FileOutputStream("homework/server/"+ UUID.randomUUID().toString()+".jpg")
            );
            int b;
            while ((b = bis.read()) != -1) {
                bos.write(b);
            }
            //通过Socket获取输出流，给出反馈
            BufferedWriter bw = new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())
            );
            bw.write("上传成功");
            bw.newLine();
            bw.flush();
            socket.shutdownOutput();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bos!= null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
